//
//  MJNetWorkTool.m
//  MJ
//
//  Created by lina on 2017/11/30.
//  Copyright © 2017年 lina. All rights reserved.
//

#import "MJNetWorkTool.h"
#import "AFNetworking.h"

@interface MJNetWorkTool ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation MJNetWorkTool

/**
 *  类方法
 */
+ (MJNetWorkTool *)sharedUtil
{
    static dispatch_once_t  onceToken;
    static MJNetWorkTool * sharedInstance;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MJNetWorkTool alloc] init];
    });
    return sharedInstance;
}

/**
 * AF网络请求
 */
- (void)requestAFURL:(NSString *)URLString httpMethod:(NSInteger)method parameters:(NSMutableDictionary *)parameters succeed:(void (^)(id response))succeed failure:(void (^)(NSError *error))failure
{
   
    if (!self.manager){self.manager = [AFHTTPSessionManager manager];}
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"text/xml", nil];
    self.manager.requestSerializer.timeoutInterval = 30;
    [self.manager.requestSerializer setValue:@"" forHTTPHeaderField:@"If-None-Match"];
    self.manager.securityPolicy = [self setupAFNSecurityPolicy];
    //每次请求都要加请求头
    NSString *baseString = [[NSUserDefaults standardUserDefaults] objectForKey:MJ_HttpUserAgent];
    if (baseString.length !=0 ){
        [self.manager.requestSerializer setValue:baseString forHTTPHeaderField:@"User-Agent"];
    }
    if ([[NSUserDefaults standardUserDefaults] boolForKey:IsLogined]){
        
        [parameters setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:MJ_Ticket]] forKey:@"ltencpass"];
    }
    [parameters setObject:MJ_API_VERSION forKey:@"ver"];
    switch (method)
    {
        case METHOD_GET:
        {
            [self.manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject)
             {
                 NSString *responseStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                 if (succeed)
                 {
                     succeed([self dictionaryWithJsonString:responseStr]);
                 }
             }failure:^(NSURLSessionDataTask *task, NSError *error)
             {
                 if (failure)
                 {
                     failure(error);
                 }
             }];
        }
            break;
            
        case METHOD_POST:
        {
            
            
            [self.manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject)
             {
                 NSString *responseStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                 NSDictionary *responDict = [self dictionaryWithJsonString:responseStr];
                 if (succeed) {
                     succeed(responDict);
                 }
             } failure:^(NSURLSessionDataTask *task, NSError *error) {
                 if (failure) {
                     failure(error);
                 }
             }];
        }
            break;
            
        default:
            break;
    }
}
- (void)requestAFURL:(NSString *)URLString
          parameters:(id)parameters
            fileName:(NSString *)imagePath
             succeed:(void (^)(id))succeed
             failure:(void (^)(NSError *))failure
{
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 8.0) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
        // 设置超时时间
        manager.requestSerializer.timeoutInterval = 30;
        //设置验证模式
        manager.securityPolicy = [self setupAFNSecurityPolicy];
        //每次请求都要加请求头
        NSString *baseString = [[NSUserDefaults standardUserDefaults] objectForKey:MJ_HttpUserAgent];
        if (baseString.length !=0 ){
            [manager.requestSerializer setValue:baseString forHTTPHeaderField:@"User-Agent"];
        }
        if ([[NSUserDefaults standardUserDefaults] boolForKey:IsLogined]){

            [parameters setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:MJ_Ticket]] forKey:@"ltencpass"];
        }
        [parameters setObject:MJ_API_VERSION forKey:@"ver"];
        [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath] name:@"file" error:nil];
        } progress:^(NSProgress * _Nonnull uploadProgress){} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
         {
             NSString *responseStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
             if (succeed) {
                 succeed([self dictionaryWithJsonString:responseStr]);
             }
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
         {
             if (failure) {
                 failure(error);
             }
         }];
    }
    else
    {
        NSString *tmpFilename = [NSString stringWithFormat:@"%f",[NSDate timeIntervalSinceReferenceDate]];
        NSURL *tmpFileUrl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:tmpFilename]];
        if ([[NSUserDefaults standardUserDefaults] boolForKey:IsLogined]){

            [parameters setObject:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:MJ_Ticket]] forKey:@"ltencpass"];
        }
        [parameters setObject:MJ_API_VERSION forKey:@"ver"];
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
            [formData appendPartWithFileURL:[NSURL fileURLWithPath:imagePath] name:@"file" error:nil];
        } error:nil];
        [[AFHTTPRequestSerializer serializer] requestWithMultipartFormRequest:request writingStreamContentsToFile:tmpFileUrl completionHandler:^(NSError * _Nullable error)
         {
             AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
             manager.responseSerializer = [AFHTTPResponseSerializer serializer];
             //每次请求都要加请求头
             NSString *baseString = [[NSUserDefaults standardUserDefaults] objectForKey:MJ_HttpUserAgent];
             if (baseString.length !=0 ){
                 [request setValue:baseString forHTTPHeaderField:@"User-Agent"];
             }
             request.timeoutInterval = 30;
             NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:tmpFileUrl progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error)
                                                   {
                                                       [[NSFileManager defaultManager] removeItemAtURL:tmpFileUrl error:nil];
                                                       if (error){
                                                           if (failure) {
                                                               failure(error);
                                                           }
                                                       }
                                                       else
                                                       {
                                                           NSString *responseStr =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                                                           if (succeed) {
                                                               succeed([self dictionaryWithJsonString:responseStr]);
                                                           }
                                                       }
                                                   }];
             [uploadTask resume];
         }];
    }
}



/*json
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableLeaves
                                                          error:&error];
    if(error) {
        return nil;
    }
    return dic;
}

- (AFSecurityPolicy *)setupAFNSecurityPolicy
{
    //在单向认证时，前端不放证书，服务器去验证
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    //如果是需要服务端验证证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    //validatesDomainName 是否需要验证域名，默认为YES；
    securityPolicy.validatesDomainName = NO;
    return securityPolicy;
}


@end
